import api from '../api';
import { ElNotification } from 'element-plus';

import { redirectToUserLogin } from "@/router/instuction"
export interface User {
    username: string;
    password: string;
}
export const register = async (user: User) => {
    try {
        const formData = new URLSearchParams();
        formData.append('username', user.username);
        formData.append('password', user.password);
        const response = await api.post('/users/register', formData);
        return response.data;
    } catch (error) {
        throw new Error('注册失败');
    }
};
export const login = async (user: User) => {
    try {
        // 参数格式化
        const formData = new URLSearchParams();
        formData.append('username', user.username);
        formData.append('password', user.password);
        const { data: response } = await api.post('/users/login', formData);
        if (response && response.status == 200) {
            console.log(response.data)
            localStorage.setItem('accessToken', response.data.accessToken);
            localStorage.setItem('refreshToken', response.data.refreshToken);
            localStorage.setItem("userId", response.data.userId);
        }
        return response.data;
    } catch (error) {
        return Promise.reject(error)
    }
};
// 验证token
export const validateToken = async (token: string) => {
    try {
        const response = await api.get(`/users/validateToken?token=${token}`);
        return response.data;
    } catch (error) {
        throw new Error('Invalid or expired token');
    }
};
export const refreshToken = async (refreshToken: string) => {
    try {
        const config = {
            headers: {
                'Authorization': `Bearer ${refreshToken}`
            }
        };
        const response = await api.post('/users/refreshToken', {}, config);
        console.log(response)
        return response.data;
    } catch (error) {
        redirectToUserLogin()
        throw new Error('Token刷新失败');

    }
};
// 获取用户详情
export const getUserDetails = async () => {
    try {
        const { data: response } = await api.get('/users/details');
        if (response && response.status == 200) {
            return response.data
        }
        return null;
    } catch (error) {
        redirectToUserLogin()
    }
};
export const logout = async () => {
    try {
        const { data: response } = await api.post('/users/logout');
        if (response.status == 200) {
            localStorage.removeItem('accessToken');
            localStorage.removeItem('refreshToken');
            localStorage.removeItem('userId');
            ElNotification.success('用户已注销成功');
            redirectToUserLogin();
        }

        return response.data;
    } catch (error) {
        ElNotification.error('登出失败');
        throw new Error('登出失败');
    }
};
// 更新用户信息
export const updateUserInfo = async (userId:string,email: string, avatar: string, bio: string, className: string, school: string) => {
    try {

        const formData = new URLSearchParams();
        if (userId) formData.append('userId',userId);

        if (email) formData.append('email', email);
        if (avatar) formData.append('avatar', avatar);
        if (bio) formData.append('bio', bio);
        if (className) formData.append('className', className);
        if (school) formData.append('school', school);
        const response = await api.post('/users/update', formData);
        return response.data;
    } catch (error) {
        throw new Error('更新用户信息失败');
    }
};

// 上传头像
export const uploadAvatar = async (file: File,userId:string) => {
    try {
        const formData = new FormData();
        formData.append('file', file);
        formData.append("userId",userId)
        const response = await api.post('/users/uploadAvatar', formData);
        return response.data;
    } catch (error) {
        throw new Error('上传头像失败');
    }
};
// 根据用户详情获取id
export const getUserDetailsById = async (userId: string) => {
    try {
        const response = await api.get(`/users/details/${userId}`);
        return response.data;
    } catch (error) {
        throw new Error('获取用户详情失败');
    }
};
// 新增上线和下线接口
export const userOnline = async (username: string) => {
    try {
        const formData = new URLSearchParams();
        formData.append('username', username);
        const response = await api.post('/users/online', formData);
        return response.data;
    } catch (error) {
        throw new Error('用户上线失败');
    }
};

export const userOffline = async (username: string) => {
    try {
        const formData = new URLSearchParams();
        formData.append('username', username);
        const response = await api.post('/users/offline', formData);
        return response.data;
    } catch (error) {
        throw new Error('用户下线失败');
    }
};